# -*- coding:utf-8 -*-
# @FileName : app\api\v1\chat\routes.py
# @Time     : 2025/11/28
# @Author   : 天空之城
"""Chat API 路由文件

此模块实现了 Chat API 的路由定义和请求处理。
"""
from flask import request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity

from . import chat_bp
from .services import save_user_message, save_ai_response, get_conversation_history, get_task_execution_detail
from .schemas import ChatSendResponseSchema, ChatHistoryResponseSchema, TaskExecutionDetailSchema
from app.services.agent_service import AgentService
from app.utils.response_factory import ResponseFactory
from app.models.conversation import Conversation
from app.extensions import db

import logging

logger = logging.getLogger(__name__)


@chat_bp.route('/send', methods=['POST'])
@jwt_required()
def send_message():
    """发送聊天消息接口
    
    接收用户消息，调用AI模型生成响应，并保存对话历史。
    
    Request Body:
        conversation_id (str): 对话ID
        message (str): 用户消息内容
        
    Returns:
        JSON: 包含对话ID、AI响应消息和任务执行ID（如果有）的响应数据
    """
    try:
        # 获取请求数据
        data = request.get_json()
        conversation_id = data.get('conversation_id')
        user_message = data.get('message')
        
        # 验证必要参数
        if not conversation_id or not user_message:
            return ResponseFactory.error(msg='缺少必要参数', code=400)
        
        # 保存用户消息
        success, error = save_user_message(conversation_id, user_message)
        if not success:
            return ResponseFactory.error(msg=f'保存用户消息失败: {error}', code=500)
        
        # 获取对话历史记录
        try:
            success, error, history_data = get_conversation_history(conversation_id)
            if not success:
                return ResponseFactory.error(msg=f'获取对话历史失败: {error}', code=500)
        except ValueError as e:
            logger.error(f"解包对话历史数据失败: {str(e)}")
            return ResponseFactory.error(msg=f'获取对话历史失败: 数据格式错误', code=500)
        except Exception as e:
            logger.error(f"调用get_conversation_history函数失败: {str(e)}")
            return ResponseFactory.error(msg=f'获取对话历史失败: {str(e)}', code=500)
        
        # 准备模型输入
        messages = history_data['messages']
        model_input = [{"role": msg["role"], "content": msg["content"]} for msg in messages]
        
        # 调用AgentService生成AI响应
        agent_service = AgentService()
        
        # 使用handle_user_message处理用户消息，获取完整的响应和工具调用日志
        result = agent_service.handle_user_message(
            conversation_id=str(conversation_id),
            user_input=user_message,
            history_messages=history_data.get('messages', [])
        )
        
        # 提取AI响应和执行ID
        ai_response = result['message']['content']
        execution_id = result['message'].get('execution_id')
        tool_execution_logs = result.get('tool_execution_logs', [])
        
        logger.info(f"对话处理完成，工具调用次数: {len(tool_execution_logs)}")
        
        # 保存AI响应消息
        success, error = save_ai_response(conversation_id, ai_response, execution_id)
        if not success:
            return ResponseFactory.error(msg=f'保存AI响应失败: {error}', code=500)
        
        # 构造响应数据
        response_data = {
            "conversation_id": conversation_id,
            "message": ai_response,
            "execution_id": execution_id,
            "tool_execution_logs": tool_execution_logs
        }
        
        # 验证并返回响应
        schema = ChatSendResponseSchema()
        result = schema.dump(response_data)
        return ResponseFactory.success(data=result, msg='消息发送成功')
        
    except Exception as e:
        logger.error(f"处理聊天消息失败: {str(e)}")
        return ResponseFactory.error(msg='处理消息失败', code=500)


@chat_bp.route('/history', methods=['GET'])
@jwt_required()
def get_history():
    """获取对话历史记录接口
    
    根据对话ID获取该对话的所有消息记录。
    
    Query Parameters:
        conversation_id (str): 对话ID
        
    Returns:
        JSON: 包含对话历史记录的响应数据
    """
    try:
        # 获取查询参数
        conversation_id = request.args.get('conversation_id')
        
        # 验证必要参数
        if not conversation_id:
            return ResponseFactory.error(msg='缺少对话ID参数', code=400)
        
        # 获取对话历史记录
        try:
            success, error, history_data = get_conversation_history(conversation_id)
            if not success:
                return ResponseFactory.error(msg=f'获取对话历史失败: {error}', code=500)
        except ValueError as e:
            logger.error(f"解包对话历史数据失败: {str(e)}")
            return ResponseFactory.error(msg=f'获取对话历史失败: 数据格式错误', code=500)
        except Exception as e:
            logger.error(f"调用get_conversation_history函数失败: {str(e)}")
            return ResponseFactory.error(msg=f'获取对话历史失败: {str(e)}', code=500)
        
        # 验证并返回响应
        schema = ChatHistoryResponseSchema()
        result = schema.dump(history_data)
        return ResponseFactory.success(data=result, msg='获取对话历史成功')
        
    except Exception as e:
        logger.error(f"获取对话历史失败: {str(e)}")
        return ResponseFactory.error(msg='获取对话历史失败', code=500)


@chat_bp.route('/task-execution/<int:execution_id>', methods=['GET'])
@jwt_required()
def get_task_execution(execution_id):
    """获取任务执行详情接口
    
    根据任务执行ID获取详细的任务执行信息和步骤记录。
    
    Path Parameters:
        execution_id (int): 任务执行ID
        
    Returns:
        JSON: 包含任务执行详情的响应数据
    """
    try:
        # 获取任务执行详情
        success, error, execution_data = get_task_execution_detail(execution_id)
        if not success:
            return ResponseFactory.error(msg=f'获取任务执行详情失败: {error}', code=500)
        
        # 验证并返回响应
        schema = TaskExecutionDetailSchema()
        result = schema.dump(execution_data)
        return ResponseFactory.success(data=result, msg='获取任务执行详情成功')
        
    except Exception as e:
        logger.error(f"获取任务执行详情失败: {str(e)}")
        return ResponseFactory.error(msg='获取任务执行详情失败', code=500)